<template>
  <view class="float-button">
    <uni-badge class="uni-badge-left-margin" :text="count" absolute="rightTop" size="small">
      <navigator url="/pages/compose/compose" hover-class="none">
        <uni-icons type="cart" size="30"></uni-icons>
      </navigator>
    </uni-badge>
  </view>
  <view class="left-right">
    <scroll-view scroll-y class="left">
      <view class="title">试卷</view>
      <uni-collapse v-for="(item_month, index) in monthPaperList" :key="index">
        <uni-collapse-item :title="item_month.name" :open="false" :show-animation="true" border>
          <view
            v-for="(item_paper, index) in item_month.children"
            :key="index"
            @tap="onClickPaper(item_paper)"
            class="item"
            :class="{ active: item_paper.id === state.paper_id }"
          >
            <text class="name">{{ item_paper.name }}</text>
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </scroll-view>
    <scroll-view class="right" scroll-y>
      <!-- <view class="subject">
        <text>学科：</text>
        <radio-group @change="subject_change">
          <label v-for="(item, index) in subject_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view> -->
      <view class="type_select">
        <text>类型：</text>
        <radio-group @change="type_change">
          <label v-for="(item, index) in type_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view>
      <scroll-view scroll-x class="year_select">
        <view class="selecct-view">
          <text>年份：</text>
          <radio-group @change="year_change">
            <label v-for="(item, index) in yearList" :key="index">
              <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
              {{ item.name }}
            </label>
          </radio-group>
        </view>
      </scroll-view>
      <view class="subject">
        <text>年级：</text>
        <radio-group @change="grade_change">
          <label v-for="(item, index) in grade_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view>
      <view class="download_paper">
        <uni-icons
          v-if="state.file != ''"
          type="cloud-download"
          size="30"
          @click="onClickDownloadFile"
          >试卷下载</uni-icons
        >
        <!-- <uni-icons v-if="state.file_explain != ''" type="cloud-download-filled" size="30"
          @click="onClickDownloadFileExpalin">解析下载</uni-icons> -->
      </view>
      <view class="content">
        <uni-card
          v-for="(item, index) in questionList"
          :key="index"
          :title="item.reference"
          class="guide-content"
          :sub-title="item.publish_time"
          :extra="item.type_cn"
        >
          <MathCanvas :mathFormula="[item.content_front]" class="uni-h6 guide-content"></MathCanvas>
          <rich-text space="nbsp" :nodes="item.images" class="uni-h6 guide-content"></rich-text>
          <!-- <text class="guide-content"></text> -->
          <text class="bank_point">库币：{{ item.bank_point }}题型：{{ item.type_cn }}</text>
          <button
            @tap="onClickAddToCompose(index)"
            size="mini"
            class="button_content"
            type="primary"
            :disabled="disabledButton(item)"
          >
            组卷
          </button>
        </uni-card>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type {
  QuestionItem,
  ExaminationPaperItem,
  SelectTypeItem,
  ExaminationMenuItem,
} from '@/types/home'
import {
  getExaminationPaperMenuListAPI,
  getQuestionNoAuthAPI,
  getQuestionByPaperAPI,
} from '@/services/home'
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app'
import UniBadge from '@dcloudio/uni-ui/lib/uni-badge/uni-badge.vue'
import { useComposeStore, useDetailStore } from '@/stores'
import { useMemberStore } from '@/stores'
import { baseURL, baseURL_noapi, download_request_get } from '@/utils/http'
import MathCanvas from '@/components/MathCanvas.vue'
// 获取会员Store
const memberStore = useMemberStore()

const menuList = ref<ExaminationMenuItem[]>([])
const twoLayerData = ref<any[]>([])
const threeLayerData = ref<any[]>([{ '2024年': [] }, { '2023年': [] }, { '2022年': [] }])
const composeButton = ref(null)
const composeStore = useComposeStore()
const detailStore = useDetailStore()
const questionList = ref<QuestionItem[]>([])
let composeList = ref<QuestionItem[]>([])
// const monthPaperList = ref<monthPaperItem[]>([])
type monthPaperItem = {
  name: string
  children: ExaminationMenuItem[]
}
// 通用性变量
const state = reactive({
  bank_point: 2,
  file: '',
  file_explain: '',
  select_grade: '0',
  select_year: '2024年',
  subject_id: 1,
  paper_id: 0,
  paper_type: 0,
  paper_title: '',
  page: 1,
  size: 10,
  total: 1,
})
// 根据选择的年份和学科， 响应式显示该年份下的月份试卷列表，用于侧边栏的折叠试卷列表
const monthPaperList = computed(() => {
  console.log('state.select_year', state.select_year)
  console.log('state.subject_id - 1', state.subject_id - 1)
  let month_paer_list: monthPaperItem[] =
    threeLayerData.value[state.subject_id - 1][state.select_year]
  console.log('month_paer_list', month_paer_list)
  if (state.select_grade == '0') {
    return month_paer_list
  } else {
    let month_paer_list_temp: monthPaperItem[] = []
    // const all_temp: monthPaperItem[] = threeLayerData.value[state.subject_id - 1][state.select_year]
    month_paer_list.forEach((element_month) => {
      let month_name = element_month.name
      let children_temp: any[] = []
      const children: ExaminationMenuItem[] = element_month.children
      children.forEach((element_paper) => {
        if (element_paper.grade == state.select_grade) {
          children_temp.push(element_paper)
        }
      })
      if (children_temp.length > 0) {
        month_paer_list_temp.push({ name: month_name, children: children_temp })
      }
    })
    if (month_paer_list_temp.length > 0) {
      return month_paer_list_temp
    } else {
      uni.showToast({ icon: 'error', title: '该年级没有试卷' })
      return month_paer_list
    }
  }
})
// 根据选择的学科，响应显示该学科下的试卷不为空的年份
const yearList = computed(() => {
  return twoLayerData.value[state.subject_id - 1]
})
// 选择框列表
const subject_list = ref<SelectTypeItem[]>([
  { name: '信息', value: '1', checked: true },
  { name: '通用', value: '2', checked: false },
  { name: '职高', value: '3', checked: false },
])
let type_list = ref<SelectTypeItem[]>([
  { name: '知识点', value: '1', checked: false },
  { name: '试卷', value: '2', checked: true },
])
const grade_list = ref<SelectTypeItem[]>([
  { name: '中考', value: '4', checked: true },
  { name: '九', value: '3', checked: false },
  { name: '八', value: '2', checked: false },
  { name: '七', value: '1', checked: false },
])
// 获取题目的知识点参数
const paperParams = reactive({
  paper_id: state.paper_id,
  page: state.page,
  size: state.size,
})
// 重新获取试题列表，重新修改参数，再发送api
const getQuestionData = async () => {
  const paperParams = {
    paper_id: state.paper_id,
    page: state.page,
    size: state.size,
  }
  console.log('获取题目的参数', paperParams)
  const res = await getQuestionByPaperAPI(paperParams)
  console.log('根据试卷id获取题目：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    questionList.value = res.results
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 试卷点击事件，重新获取该试卷的试题
const onClickPaper = (paper: ExaminationMenuItem) => {
  console.log('试卷改变了：', paper)
  state.bank_point = paper.bank_point
  state.file = paper.file
  state.file_explain = paper.file_explain
  state.paper_id = paper.id
  state.paper_title = paper.name
  state.total = 0
  state.page = 1
  getQuestionData()
}
// 下载试卷文件
const onClickDownloadFile = () => {
  console.log('下载文件', state.file)
  // let user_bank_point = memberStore.profile!.value?.bank_point
  if (state.bank_point > 0) {
    uni.showToast({ icon: 'error', title: '你的库币余额不足，无法下载' })
    return 0
  }
  if (state.file !== '') {
    uni.showLoading({ title: '下载中...' })
    const url = baseURL_noapi + state.file
    let current_date = new Date()
    let date =
      current_date.getFullYear() +
      '-' +
      (current_date.getMonth() + 1).toString() +
      '-' +
      current_date.getDate()
    let new_file_name = date + state.paper_title + '.pdf'
    let params_data = { paper_id: state.paper_id }
    download_request_get(params_data, url, new_file_name)
    // download(url)
  }
}
// 下载试卷解析文件
const onClickDownloadFileExpalin = () => {
  console.log('下载解析文件', state.file_explain)
  // let user_bank_point = memberStore.profile!.bank_point
  if (state.bank_point > 0) {
    uni.showToast({ icon: 'error', title: '你的库币余额不足，无法下载' })
    return 0
  }
  if (state.file_explain !== '') {
    uni.showLoading({ title: '下载中...' })
    const url = baseURL + '/' + state.file_explain
    let current_date = new Date()
    let date =
      current_date.getFullYear() +
      '-' +
      (current_date.getMonth() + 1).toString() +
      '-' +
      current_date.getDate()
    let new_file_name = date + state.paper_title + '_解析.pdf'
    let params_data = { paper_id: state.paper_id }
    download_request_get(params_data, url, new_file_name)
    // download(url)
  }
}
// 选中题目个数，利用计算属性
const count = computed(() => {
  return composeList.value.length
})
// 年级改变了，重新筛选该年级下的试卷列表
const grade_change = (e: any) => {
  state.select_grade = e.target.value
  console.log('年级改了', state.select_grade)
}
// 年份改变了，重新获取左侧的试卷列表
const year_change = (e: any) => {
  state.select_year = e.target.value
  console.log('年份改了', state.select_year)
}
// 学科改变了,重新获取该学科的知识点
const subject_change = (e: any) => {
  console.log('学科改变：', e.target.value)
  state.subject_id = e.target.value
}
// 组卷方式改变了，切换到该页面或tarbar，根据选择的值判断
const type_change = (e: any) => {
  // console.log('组卷方式改变：', e.target.value)
  if (parseInt(e.target.value) == 1) {
    uni.switchTab({ url: '/pages/compose/chapter' })
  }
}
// 把题目添加到组卷车中
const onClickAddToCompose = (index: number) => {
  if (composeList.value.length < 50) {
    composeList.value.push(questionList.value[index])
    composeStore.setCompose(composeList.value)
  } else {
    uni.showToast({ icon: 'error', title: '最多只能添加50道题目！' })
  }
}
// 判断该试题是否已经在组卷列表中，如果在则不可用，避免加入重复的题目
const disabledButton = (item: any) => {
  let flag = composeList.value.includes(item)
  return flag
}
// 点击卡片事件，把试题信息保存到缓存中，切换到详情页面
const onClickCard = (item: QuestionItem) => {
  // console.log('浏览题目', item)
  detailStore.setDetail(item)
  uni.navigateTo({ url: '/pages/compose/detail' })
}
// 无凭证获取题目，用于首次获取题目
const getQuestionNoAuthData = async () => {
  const res = await getQuestionNoAuthAPI()
  // console.log('根据知识点获取题目：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    questionList.value = res.results
    state.total = res.count
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 获取三级嵌套数组，即年份月份和试卷基本信息
const getMenuListData = async () => {
  const res = await getExaminationPaperMenuListAPI()
  console.log('获取三级嵌套数组：', res)
  // console.log('res.code', res.code)
  if (res.code == 200) {
    uni.showToast({ icon: 'success', title: '请选择年份' })
    menuList.value = res.data.results
    const [twoLayerData_temp, threeLayerData_temp] = createYearMonthPaperDic()
    twoLayerData.value = twoLayerData_temp
    threeLayerData.value = threeLayerData_temp
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 创建根据以年月为key，试卷列表为value的字典
const createYearMonthPaperDic = () => {
  let three_layer: any[] = [{}, {}, {}]
  let two_layer: any[] = [[], [], []]
  menuList.value.forEach((element_year) => {
    let year_name: string = element_year.name
    let year_key_list: any[] = [{}, {}, {}]
    for (let i = 0; i < 3; i++) {
      year_key_list[i][year_name] = []
    }
    let year_children = element_year.children
    year_children.forEach((element_month) => {
      let month_name = element_month.name
      // 月临时列表，分别存放3个学科的字典
      let month_list_temp: any[] = [
        { name: month_name, children: [] },
        { name: month_name, children: [] },
        { name: month_name, children: [] },
      ]
      let month_children = element_month.children
      month_children.forEach((element_paper) => {
        if (!two_layer[element_paper.subject - 1].includes(year_name)) {
          two_layer[element_paper.subject - 1].push(year_name)
        }
        month_list_temp[element_paper.subject - 1]['children'].push(element_paper)
      })
      // 把该月的试卷列表，即按学科分类后的数据扁平化填入三层嵌套数组
      for (let i = 0; i < 3; i++) {
        if (month_list_temp[i]['children'].length > 0) {
          year_key_list[i][year_name].push(month_list_temp[i])
        }
      }
    })
    // 一年数据遍历完，把该年3个学科扁平化填入三层嵌套数组
    for (let i = 0; i < 3; i++) {
      if (year_key_list[i][year_name].length > 0) {
        three_layer[i][year_name] = year_key_list[i][year_name]
      }
    }
  })
  // 把二层嵌套数组年份的年份字符串转换成字典，为了适配选择框
  let two_layer_select: any[] = [[], [], []]
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < two_layer[i].length; j++) {
      two_layer_select[i].push({
        name: two_layer[i][j],
        value: two_layer[i][j],
        checked: false,
      })
    }
  }
  return [two_layer_select, three_layer]
}
// 页面显示触发，加载缓存中的已选题目
onShow(() => {
  composeList.value = composeStore.compose
  type_list.value[0].checked = false
  type_list.value[1].checked = true
  console.log('united缓存中的题目：', composeStore.compose)
})
// 页面加载
onLoad(async () => {
  // console.log('页面加载')
  getMenuListData()
  getQuestionNoAuthData()
})
// 用于上拉触底新增试题数据
const addQuestionData = async () => {
  let paperParams = {
    paper_id: state.paper_id,
    page: state.page + 1,
    size: state.size,
  }
  const res = await getQuestionByPaperAPI(paperParams)
  console.log('根据试卷id获取题目：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    questionList.value.push(...res.results)
    state.page += 1
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '触底添加数据失败' })
  }
}
// 自定义触底加载更多数据
onReachBottom(async () => {
  console.log('触底拉')
  if (questionList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    addQuestionData()
  }
})
onPullDownRefresh(async () => {
  console.log('下拉刷新')
  state.page = 1
  getQuestionData()
  uni.stopPullDownRefresh()
})
</script>
<style lang="scss" scoped>
.fab {
  ::v-deep.uni-icons.uniui-plusempty.fab-circle-icon {
    font-size: 12 !important;
  }

  ::v-deep.uniui-plusempty:before {
    content: '组卷' !important;
    font-size: 12px;
  }
}

.left-right {
  display: flex;
  flex: 1;
  min-height: 400rpx;
}

.left {
  // display: flex;
  flex: none;
  width: 180rpx;
  overflow: hidden;
  background-color: #f6f6f6;

  .item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80rpx;
    font-size: 25rpx;
    color: #596c63;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      left: 42rpx;
      bottom: 0;
      width: 96rpx;
      border-top: 1rpx solid #e3e4e7;
    }
  }

  .active {
    background-color: fff;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 8rpx;
      height: 100%;
      background-color: #0bba88d7;
    }
  }

  .title {
    font-size: 28rpx;
    font-weight: bold;
    overflow: hidden;
  }
}

.left .item:last-child::after,
.left .active::after {
  display: none;
}

.name {
  padding: 3rpx;
  font-size: 25rpx;
  color: #333;
}

.right {
  overflow-y: scroll;
  font-size: 28rpx;
  padding: 1rpx;

  .button_content {
    font-size: 25rpx;
    text-align: left;
  }
}

.subject {
  font-size: 30rpx;
  display: flex;
  flex-flow: row nowrap;
}

.type_select {
  font-size: 30rpx;
  display: flex;
  flex-flow: row nowrap;
}

.selecct-view {
  display: flex;
  flex-flow: row nowrap;
}

.year_select {
  font-size: 30rpx;
}

.content {
  font-size: 27rpx;
  display: flex;
  flex-flow: row wrap;
  height: 100vh;
}

.guide-content {
  font-size: 27rpx;
  display: flex;
  flex-flow: column nowrap;
}

.bank_point {
  font-size: 27rpx;
  color: green;
  display: flex;
  flex-flow: column nowrap;
}

.float-button {
  position: absolute;
  z-index: 999;
  left: 10px;
  top: 10px;
  width: 30px;
  height: 30px;
  background-color: white;
  color: white;
  text-align: center;
  line-height: 30px;
  border-radius: 25px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.uni-badge-left-margin {
  margin-left: 0px;
}

.twoButton .download_paper {
  display: flex;
  flex-flow: row nowrap;
  align-items: space-between;
  justify-items: center;
}
</style>
